package io.gitee.macxiang.controller;

import java.io.File;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import io.gitee.macxiang.config.MacConfig;
import io.gitee.macxiang.utils.Datas;
import io.gitee.macxiang.utils.utils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

@RestController
public class DefController {
  @Autowired
  MacConfig config;

  /** 自动post请求处理
   * @param request     HttpServletRequest
   * @param response    HttpServletResponse
   * @return            返回结果
   */
  @PostMapping("/**")
  public Object autoPost(HttpServletRequest request, HttpServletResponse response) {
    String uri = request.getRequestURI();
    if (uri.indexOf(config.controller.prefix) == 0) {
      String[] ss = uri.substring(config.controller.prefix.length()).split("/");
      String tableName = null, methodName = null;
      if (ss.length == 2) {
        tableName = ss[0];
        methodName = ss[1];
      } else if (ss.length == 3) {
        tableName = ss[1];
        methodName = ss[2];
      }
      if (tableName != null && methodName != null) {
        return utils.controller.post(tableName, methodName, utils.request2json(request), request.getHeader("token"));
      }
    }
    response.setStatus(HttpServletResponse.SC_NOT_FOUND);
    return null;
  }

  /** 自动Get请求处理
   * @param request     HttpServletRequest
   * @param response    HttpServletResponse
   * @throws  Exception 抛出异常
   */
  @GetMapping("/**")
  public void get(HttpServletRequest request, HttpServletResponse response) throws Exception {
    String str = "public" + request.getRequestURI();
    str = Datas.formatFilename(str, false);
    String mime = Datas.formatFilename("public", true);
    if (str.indexOf(mime) != 0) {
      throw new RuntimeException("路径非法");
    }
    mime = Datas.mime(str.substring(str.lastIndexOf(".") + 1));
    File fi = new File(str);
    while (!fi.exists() || fi.isDirectory()) {
      str += "/index.html";
      try {
        fi = new File(str);
        if (!fi.exists()) {
          str = Datas.formatFilename("public/index.html", false);
          fi = new File(str);
          if (fi.exists()) {
            break;
          }
          utils.out(HttpStatus.NOT_FOUND.getReasonPhrase(), HttpStatus.NOT_FOUND.value());
        }
      } catch (Exception e) {
        utils.out(e);
      }
    }
    System.out.println(13);
    byte[] d = Datas.readFile(str);
    response.setHeader("Content-type", Datas.mime("txt"));
    response.setHeader("content-type", mime);
    response.getOutputStream().write(d);
  }
}
